package com.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro内置过滤器
        Map<String, String> filterMap = new LinkedHashMap<>();

        //user 用户，add 权限可访问
        filterMap.put("/user/add","perms[user:add]");  //默认跳转未授权

        filterMap.put("/user/del","perms[user:del]");

        filterMap.put("/user/*","authc");   //需要认证才能访问

        factoryBean.setFilterChainDefinitionMap(filterMap);

        //        设置登录请求
        factoryBean.setLoginUrl("/doLogin");
        //        设置未授权
        factoryBean.setUnauthorizedUrl("/unauth");

        return factoryBean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联 realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm 对象
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合ShiroDialect   shiro-thymeleaf整合
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
